<template>
  <div>
    <el-tree
      ref="tree"
      default-expand-all
      check-strictly
      show-checkbox
      :data="list"
      :props="{label:'name'}"
      node-key="id"
    />
    <el-button @click="hSubmit">确认</el-button>
    <el-button @click="hCancel">取消</el-button>
  </div>
</template>
<script>
import { tranListToTreeData } from '@/utils/index.js'
import { getPermission } from '@/api/permission'
import { getRoleById, assignPremission } from '@/api/settings'
// 1. 打开子组件，获取数据
// 2. 数据转换： 数组-> 树
// 3. 铺设数据到el-tree
export default {
  props: { id: { type: String, default: '' }},
  data() {
    return {
      list: []
    }
  },
  created() {
    this.loadPermission()
    // 获取默认的权限数据
    // this.loadPermissionById()
  },
  methods: {
    async loadPermissionById() {
      const res = await getRoleById(this.id)

      console.log('获取当前角色的权限数据', res)

      // 回填： 调用el-tree的setCheckedKeys方法
      this.$refs.tree.setCheckedKeys(res.data.permIds)
    },
    async loadPermission() {
      const res = await getPermission()
      // 数据转换： 数组-> 树
      this.list = tranListToTreeData(res.data)
      console.log('打开子组件，获取数据', res)
    },
    hCancel() {
      // 通知父组件关闭弹层
      this.$emit('close')
    },
    async hSubmit() {
      // 1. 获取用户的选择
      const ids = this.$refs.tree.getCheckedKeys()
      // 2. 调用接口
      const res = await assignPremission({ id: this.id, permIds: ids })
      console.log(' 调用接口', res)

      // 3. 通知父组件
      this.$emit('success')

      this.$message.success('分配权限成功')
    }
  }
}
</script>
